"""API 客户端模块"""
import json
import platform
import requests
from colorama import Fore

from config.settings import Config
from common.tools.get_keywords import get_keywords


class APIClient:
    """API 客户端类"""
    
    def __init__(self):
        self.base_url = Config.get_api_base_url()
        self.headers = {'content-type': 'application/json'}
    
    def get_version(self):
        """获取版本信息"""
        url = f"{self.base_url}/user/get_version"
        response = requests.get(url)
        return response.json()
    
    def login(self, username, password):
        """用户登录"""
        url = f"{self.base_url}/user/cli_login"
        data = {
            "username": username,
            "password": password,
            "mac": platform.node()
        }
        json_str = json.dumps(data)
        response = requests.post(url, data=json_str, headers=self.headers)
        return response.json()
    
    def get_question_answer(self, question):
        """从题库查询答案"""
        url = f"{self.base_url}/user/get_question_answer"
        words = get_keywords(question)
        params = {
            "page": 1,
            "pageSize": 5,
            "words": words,
            "question": question
        }
        response = requests.get(url, params=params)
        response_data = response.json()
        
        if response_data["status"] == 200:
            if response_data["data"]["type"] == 'content':
                print('│ 查询方式：' + Fore.GREEN + '全文查询')
            elif response_data['data']['type'] == 'words':
                print('│ 查询方式：' + Fore.RED + '关键词查询')
                print('│ 关键词：' + Fore.RED + words)
            print('│ ————————————————')
            
            rows = response_data['data']['rows']
            for i, row in enumerate(rows, 1):
                print('│ 题库题目：' + Fore.YELLOW + row['question'])
                print('│ 题目答案：' + Fore.GREEN + row['answer'])
                print('│ 上传作者：' + row['author'])
                if i < len(rows):
                    print(' —————')
            print('├───────────────────────────')
            print('│ ' + Fore.GREEN + '题库查询完成！')
            return True
        return False

    def get_question_answer_detail(self, question):
        """从题库查询答案（返回完整JSON数据，不做任何打印），供自动版使用"""
        url = f"{self.base_url}/user/get_question_answer"
        words = get_keywords(question)
        params = {
            "page": 1,
            "pageSize": 5,
            "words": words,
            "question": question
        }
        response = requests.get(url, params=params)
        try:
            return response.json()
        except Exception:
            return {
                "status": -1,
                "msg": "parse error",
                "data": None
            }
